﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Commands.Scheduling;

namespace Commands.Settings
{
    public class SettingsSerializer<T> where T : class
    {
        public void SaveSettings(string filename, T settings)
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            var textStream = new FileStream(filename, FileMode.Create);
            serializer.Serialize(textStream, settings);
            textStream.Close();
        }

        public T LoadSettings(string filePath)
        {
            Debug.Assert(filePath != null);

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Settings));
            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                return serializer.Deserialize(fs) as T;
            }
        }
        private static T _Deserialize<T>(string text)
        {
            Debug.Assert(text != null);

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text)))
            {
                obj = (T)serializer.ReadObject(ms);
            }

            return obj;
        }
    }
}
